//
//  SparkChainConfig.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/26.
//  Copyright © 2025 考拉🐨. All rights reserved.
//
// 科大讯飞接口文档
// https://app.apifox.com/project/3774108/apis/api-134421212-run?branchId=3405977
// https://www.xfyun.cn/doc/asr/ifasr_new/API.html#_2、查询结果
import Foundation

class SparkChainConfig: NSObject {
    
    /// 科大讯飞 语音转写 上传音频文件
    /// 首先调用文件上传接口，上传待转写音频文件的基本信息（文件名、大小等）和相关的可配置参数。
    /// - Parameters:
    ///   - fileUrl: 音频文件路径
    ///   - language: 音频文件的语言种类，中文：cn，俄语：ru
    ///   - completionHandler: 转写后的文本内容
    static func uploadFile(fileUrl: String, language: String, completionHandler: @escaping (Bool, String) -> Void) {
        let appId = "9b1b2dfd"
        let appKey = "5b5806712e5a0d6e68cc5d28e5c2e2d7"
        let target = SparkChainApi.uploadFile(appId: appId, appKey: appKey, filePath: fileUrl, language: language)
        YLRequest.request(target) { result in
            switch result {
            case .success(let res):
                let dataDictionary = res.dataDictionary
                xLog(dataDictionary as NSDictionary)
                
                let code = dataDictionary["code"] as! String
                let descInfo = dataDictionary["descInfo"] as! String
                
                if code == "000000" {
                    // 上传成功
                    let content = dataDictionary["content"] as! [String: Any]
                    let orderId = content["orderId"] as! String
                    
                    SparkChainConfig.getResult(appId: appId, appKey: appKey, orderId: orderId, completionHandler: completionHandler)
                    
                } else {
                    completionHandler(false, "code：\(code) descInfo: \(descInfo)")
                }
                
            case .failure(_):
                completionHandler(false, "接口请求失败1")
            }
        }
    }
    
    
    /// 科大讯飞，上传音频文件调用成功，返回订单ID（orderId，用于查询结果或者联调排查问题时使用），是后续接口的必传参数。
    /// - Parameters:
    ///   - appId: appId description
    ///   - appKey: appKey description
    ///   - orderId: 上传音频文件调用成功，返回的订单ID
    ///   - completionHandler: 转写后的文本内容
    private static func getResult(appId: String, appKey: String, orderId: String, completionHandler: @escaping (Bool, String) -> Void) {
        // 间隔 2 秒，防止订单没有处理完成，
        DispatchQueue.main.asyncAfter(wallDeadline: .now() + 2) {
            let target = SparkChainApi.getResult(appId: appId, appKey: appKey, orderId: orderId, resultType: "transfer")
            YLRequest.request(target) { result in
                switch result {
                case .success(let res):
                    let dataDictionary = res.dataDictionary
                    xLog(dataDictionary as NSDictionary)
                    let code = dataDictionary["code"] as! String
                    if code == "000000" {
                        // 上传成功
                        let content = dataDictionary["content"] as! [String: Any]
                        let orderInfo = content["orderInfo"] as! [String: Any]
                        let status = orderInfo["status"] as! Int
                        //  订单流程状态
                        //  0：订单已创建
                        //  3：订单处理中
                        //  4：订单已完成
                        //  -1：订单失败
                        xLog("科大讯飞 订单状态 \(status)")
                        if status == 4 {
                            let orderResult = content["orderResult"] as! String
                            var result: String = ""
                            // 根据返回结果，解析字符串
                            if let resultDic = orderResult.toDictionary() {
                                let lattices = resultDic["lattice"] as! [[String: Any]]
                                lattices.forEach { latticeDic in
                                    let json_1best = latticeDic["json_1best"] as! String
                                    if let jsonBestDic = json_1best.toDictionary() {
                                        let stDic = jsonBestDic["st"] as! [String: Any]
                                        let rtArr = stDic["rt"] as! [[String: Any]]
                                        rtArr.forEach { rtDic in
                                           let wsArr = rtDic["ws"] as! [[String: Any]]
                                            wsArr.forEach { ws in
                                                let cwArr = ws["cw"] as! [[String: Any]]
                                                cwArr.forEach { cwDic in
                                                    let w = cwDic["w"] as! String
                                                    result.append(w)
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            completionHandler(true, result)
                            
                        } else if status == 3 {
                            xLog("科大讯飞 订单处理中，重新获取结果")
                            SparkChainConfig.getResult(appId: appId, appKey: appKey, orderId: orderId, completionHandler: completionHandler)
                            
                        } else if status == -1 {
                            xLog("科大讯飞 订单失败")
                            completionHandler(false, "订单失败")
                        }
                        
                    } else {
                        // {
                        //     "code": "26601",
                        //     "descInfo": "非法应用信息|signa verify fail"
                        // }
                        let descInfo = dataDictionary["descInfo"] as! String
                        completionHandler(false, "code：\(code) descInfo: \(descInfo)")
                    }
                    
                case .failure(let err):
                    completionHandler(false, "接口请求失败2")
                }
            }
        }
    }
    
    // 获取音频时长（秒）
    static func getAudioDuration(url: URL) -> Int {
        let asset = AVAsset(url: url)
        let duration = asset.duration
        let seconds = CMTimeGetSeconds(duration)
        print("音频时长：\(seconds) 秒")
        return Int(seconds)
    }
    
    
    /// 生成签名
    /// - Parameters:
    ///   - appId: appId description
    ///   - appKey: appKey description
    /// - Returns: （时间戳，签名）
    static func createSigna(appId: String, appKey: String) -> (String, String) {
        // 时间戳
        let timestamp = String(Date.sg.timestamp())
        xLog("时间戳 \(timestamp)")
        // ① 获取baseString
        let baseString = appId + timestamp
        // ② 对 baseString 进行 MD5
        let md5String = baseString.sg.md5Encrypt()
        // ③ 以 secret key 为 key 对 MD5 之后的 baseString 进行 HmacSHA1 加密，然后再对加密后的字符串进行 base64 编码。
        xLog("md5String \(md5String)")
        let signa = CryptoHelper.hmacSHA1(md5String, key: appKey)
        xLog("signa : \(signa)")
        return (timestamp, signa)
    }
    
    
    
}

/**
 {
   "code" : "000000",
   "content" : {
     "orderInfo" : {
       "expireTime" : 1743306278000,
       "failType" : 0,
       "orderId" : "DKHJQ202503271146334684mv0vmG30WgW0RI8",
       "originalDuration" : 3,
       "realDuration" : 3326,
       "status" : 4
     },
     "orderResult" : "{\"lattice\":[{\"json_1best\":\"{\\\"st\\\":{\\\"sc\\\":\\\"0.00\\\",\\\"pa\\\":\\\"0\\\",\\\"rt\\\":[{\\\"ws\\\":[{\\\"cw\\\":[{\\\"w\\\":\\\"这样\\\",\\\"wp\\\":\\\"n\\\",\\\"wc\\\":\\\"0.0000\\\"}],\\\"wb\\\":37,\\\"we\\\":72},{\\\"cw\\\":[{\\\"w\\\":\\\"发\\\",\\\"wp\\\":\\\"n\\\",\\\"wc\\\":\\\"0.0000\\\"}],\\\"wb\\\":73,\\\"we\\\":92},{\\\"cw\\\":[{\\\"w\\\":\\\"消息\\\",\\\"wp\\\":\\\"n\\\",\\\"wc\\\":\\\"0.0000\\\"}],\\\"wb\\\":93,\\\"we\\\":180},{\\\"cw\\\":[{\\\"w\\\":\\\"。\\\",\\\"wp\\\":\\\"p\\\",\\\"wc\\\":\\\"0.0000\\\"}],\\\"wb\\\":180,\\\"we\\\":180},{\\\"cw\\\":[{\\\"w\\\":\\\"\\\",\\\"wp\\\":\\\"g\\\",\\\"wc\\\":\\\"0.0000\\\"}],\\\"wb\\\":180,\\\"we\\\":180}]}],\\\"bg\\\":\\\"840\\\",\\\"rl\\\":\\\"0\\\",\\\"ed\\\":\\\"2690\\\"}}\"}],\"lattice2\":[{\"lid\":\"0\",\"end\":\"2690\",\"begin\":\"840\",\"json_1best\":{\"st\":{\"sc\":\"0.00\",\"pa\":\"0\",\"rt\":[{\"nb\":\"1\",\"nc\":\"1.0\",\"ws\":[{\"cw\":[{\"w\":\"这样\",\"wp\":\"n\",\"wc\":\"0.0000\"}],\"wb\":37,\"we\":72},{\"cw\":[{\"w\":\"发\",\"wp\":\"n\",\"wc\":\"0.0000\"}],\"wb\":73,\"we\":92},{\"cw\":[{\"w\":\"消息\",\"wp\":\"n\",\"wc\":\"0.0000\"}],\"wb\":93,\"we\":180},{\"cw\":[{\"w\":\"。\",\"wp\":\"p\",\"wc\":\"0.0000\"}],\"wb\":180,\"we\":180},{\"cw\":[{\"w\":\"\",\"wp\":\"g\",\"wc\":\"0.0000\"}],\"wb\":180,\"we\":180}]}],\"pt\":\"reserved\",\"bg\":\"840\",\"si\":\"0\",\"rl\":\"0\",\"ed\":\"2690\"}},\"spk\":\"段落-0\"}]}",
     "taskEstimateTime" : 0
   },
   "descInfo" : "success"
 }
 */
